﻿using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;

namespace Pixeldyne.Core.Extensions
{
	public static class Other
	{
		public static bool Equals(Type type1, Type type2)
		{
			return (type1 == type2);
		}

		public static string ToLittleEndian(this byte[] result)
		{
			if (!BitConverter.IsLittleEndian)
			{
				Array.Reverse(result);
			}

			return BitConverter.ToUInt32(result, 0).ToString("X8").ToLower();
		}

		/// <summary>
		/// Converts an object into an array of bytes. Object must be serializable.
		/// </summary>
		/// <param name="value">Object to serialize. May be null.</param>
		/// <returns>Serialized object, or null if input was null.</returns>
		public static byte[] ToByteArray(this object value)
		{
			if (value == null)
			{
				return null;
			}

			byte[] inMemoryBytes;

			using (var inMemoryData = new MemoryStream())
			{
				new BinaryFormatter().Serialize(inMemoryData, value);
				inMemoryBytes = inMemoryData.ToArray();
			}

			return inMemoryBytes;
		}

		/// <summary>
		/// Converts a byte array into an object. 
		/// </summary>
		/// <param name="serializedObject">Object to deserialize. May be null.</param>
		/// <returns>Deserialized object, or null if input was null.</returns>
		public static object ToObject(this byte[] serializedObject)
		{
			if (serializedObject == null || serializedObject.Length == 0)
			{
				return null;
			}

			using (var dataInMemory = new MemoryStream(serializedObject))
			{
				return new BinaryFormatter().Deserialize(dataInMemory);
			}
		}
	}
}
